/**
 * 微信socket
 */
const Promise = require("./promise").Promise;

function wxSocket(params) {
  let defaults = {
    url: "wss://10.3.201.221:15449", // 开发者服务器接口地址，必须是 wss 协议，且域名必须是后台配置的合法域名
    heander: {}, // HTTP Header , header 中不能设置 Referer
    method: "GET", // 默认是GET，有效值：OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    protocols: [], // 子协议数组,
    complete: () => {} // 接口调用结束的回调函数（调用成功、失败都会执行）
  }
  const options = Object.assign(defaults, params);
  function socket(resolve, reject) {
    // 链接socket
    const SocketTask = wx.connectSocket(options);
    // 初始化socket包装对象
    const _socket = Socket({
      task: SocketTask,
      params: params
    });
    // 连接成功监听
    wx.onSocketOpen(res => {
      _socket.setMsg(res);
      resolve(_socket);
    });
    // 链接失败监听
    wx.onSocketError(res => {
      _socket.setMsg(res);
      reject(_socket);
    });
    
  }
  return Promise(socket);
}




function Socket(options) {
  if (!(this instanceof Socket)) return new Socket(options);
  // 保存创建socket成返回的实例
  this.task = options.task;
  // 保存创建socket的参数
  this.params = options.params;
  this.msg = "";
}
/**
 * 重连
 */
Socket.prototype.reconnection = function() {
  wxSocket(this.params);
}


/**
 * 发送数据
 * @param {Object} data 发送的数据包
 */
Socket.prototype.sendSocketMessage = function(data) {
  wx.sendSocketMessage(data);
}
/**
 * 接受数据
 * @param {function} fn 接受回调函数
 */
Socket.prototype.onSocketMessage = function(fn) {
  wx.onSocketMessage(fn);
}
/**
 * 关闭socket
 * @param {Object} obj 关闭链接参数对象
 */
Socket.prototype.closeSocket = function(obj) {
  wx.closeSocket(obj);
}
/**
 * 监听socket关闭
 * @param {function} fn 监听函数
 */
Socket.prototype.onSocketClose = function(fn) {
  wx.onSocketClose(fn);
}

Socket.prototype.setMsg = function (msg) {
  this.msg = msg;
}
Socket.prototype.getMsg = function (msg) {
  return this.msg;
}

exports.wxSocket = wxSocket;